package com.webjavamail.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

public class SendMailServlet extends HttpServlet {

	private static final long serialVersionUID = -1383492105184566119L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 发送普通邮件（不带附件不是HTML的）
		SimpleEmail email = new SimpleEmail();
		email.setHostName("smtp.163.com");
		email.setAuthentication("username", "password");
//		email.setHostName("smtp.sina.com");
//		email.setAuthentication("jqbhesn@sina.com", "xiaodong");
//		email.setAuthentication("jqbhesn", "xiaodong");
		email.setCharset("utf-8");
		try {
			email.addTo(request.getParameter("to"));
			email.setFrom(request.getParameter("from"));
			email.setSubject(request.getParameter("title"));
			email.setMsg(request.getParameter("content"));
			email.send();
			request.setAttribute("sendmail.message", "邮件发送成功！");
		} catch (EmailException e) {
			e.printStackTrace();
			request.setAttribute("sendmail.message", "邮件发送失败！");
		}
		request.getRequestDispatcher("/sendResult.jsp").forward(request,
				response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
